//
//  UILabel+Image.m
//  SchoolHelper
//
//  Created by 任辰东 on 2023/11/14.
//  Copyright © 2023 JSY. All rights reserved.
//

#import "UILabel+Image.h"

@implementation UILabel (Image)

/**
 为UILabel首部设置图片标签
 
 @param text 文本
 @param images 标签数组
 @param span 标签间距
 */
-(void)setText:(NSString *)text frontImages:(NSArray<UIImage *> *)images imageSpan:(CGFloat)span
{
    NSMutableAttributedString *textAttrStr = [[NSMutableAttributedString alloc] init];
    
    for (UIImage *img in images) {//遍历添加标签
        
        NSTextAttachment *attach = [[NSTextAttachment alloc] init];
        attach.image = img;
        ///方式一：
        //计算图片大小，与文字同高，按比例设置宽度
        CGFloat imgH = self.font.lineHeight;
        CGFloat imgW = (img.size.width / img.size.height) * imgH;
        attach.bounds = CGRectMake(0, self.font.descender , imgW, imgH);
        
        //方式二：（可验证： lineHeight = ascender + descender）
//        CGFloat imgH = self.font.lineHeight;
//        CGFloat imgW = (img.size.width / img.size.height) * imgH;
//        //计算文字padding-top ，使图片垂直居中
//        CGFloat textPaddingTop = (self.font.lineHeight - self.font.ascender);
//        attach.bounds = CGRectMake(0, -textPaddingTop, imgW, imgH);
        
        NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:attach];
        [textAttrStr appendAttributedString:imgStr];
        //标签后添加空格 图片与图片/文字之间的间距(占位1个字符)
        [textAttrStr appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
    }
    
    //设置显示文本
    [textAttrStr appendAttributedString:[[NSAttributedString alloc]initWithString:text]];
    //设置间距:最后一个图片与文字的间距
    if (span != 0) {
        [textAttrStr addAttribute:NSKernAttributeName value:@(span)
                            range:NSMakeRange(0, images.count * 2/*（图片+1个空格字符）：由于图片也会占用一个单位长度,所以带上空格数量，需要 *2 */)];
    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];        //设置行间距
    [paragraphStyle setLineBreakMode:self.lineBreakMode];
    [paragraphStyle setAlignment:self.textAlignment];
    
    [textAttrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    
    self.attributedText = textAttrStr;
}

@end
